#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>

char msg[]="hello";
sem_t sem;
pthread_mutex_t mutex;

void* func(void* arg){
	sem_wait(&sem);
	pthread_mutex_lock(&mutex);
	printf("%x: %s\n",pthread_self(),(char*)arg);
	pthread_mutex_unlock(&mutex);
	sleep(3);
	pthread_exit("thread exit now\n");
}

int main(){
	pthread_t th;
	void* result;
	int ret;

	ret=sem_init(&sem,0,0);
	if(ret!=0){
		perror("sem init error\n");
		exit(-1);
	}

	ret=pthread_create(&th,NULL,func,(void*)msg);
	ret=pthread_mutex_init(&mutex,NULL);

	if(ret!=0){
		perror("thread create failed\n");
		exit(EXIT_FAILURE);
	}
	printf("we post sem \n");
	sem_post(&sem);
	ret=pthread_join(th,&result);
	if(ret!=0){
		perror("join error");
		exit(EXIT_FAILURE);
	}
	printf("thread return :%s\n",(char*)result);
	pthread_mutex_destroy(&mutex);
	exit(EXIT_SUCCESS);
}
	
